class AIManager:
    """AI助手管理器类 - 负责管理所有AI助手的操作"""

    def __init__(self, max_size=100):
        self.assistants = []
        self.max_size = max_size

    def add_assistant(self, assistant):
        if len(self.assistants) >= self.max_size:
            print("❌ 助手数量已达上限，无法添加新助手！")
            return False

        # 检查ID是否重复
        for existing in self.assistants:
            if existing.id == assistant.id:
                print("❌ 助手ID已存在，请使用不同的ID！")
                return False

        self.assistants.append(assistant)
        print(f"✅ 助手【{assistant.name}】添加成功！")
        return True

    def find_assistant_by_id(self, assistant_id):
        for assistant in self.assistants:
            if assistant.id == assistant_id:
                return assistant
        return None

    def show_all_assistants(self):
        if not self.assistants:
            print("暂无AI助手数据。")
            return

        print("所有AI助手列表：")
        for i, assistant in enumerate(self.assistants, 1):
            print(f"{i}. {assistant}")

    def show_assistant_details(self, assistant_id):
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            print(f"✅ 查询结果: {assistant}")
        else:
            print("❌ 未找到对应的AI助手！")

    def modify_assistant(self, assistant_id, attribute, value):
        assistant = self.find_assistant_by_id(assistant_id)
        if not assistant:
            print("❌ 未找到对应的AI助手！")
            return False

        attribute = attribute.lower()
        if attribute == "name":
            assistant.name = value
        elif attribute == "type":
            print("❌ 助手类型不能直接修改！如需修改类型，请删除后重新添加。")
            return False
        elif attribute == "version":
            assistant.version = value
        elif attribute == "online":
            assistant.online = value.lower() in ["1", "是", "true", "在线"]
        elif attribute == "score":
            try:
                assistant.score = int(value)
            except ValueError:
                print("❌ 能力评分必须是数字！")
                return False
        else:
            print("❌ 无效的属性名！")
            return False

        print(f"✅ 助手【{assistant_id}】修改成功！")
        return True

    def delete_assistant(self, assistant_id):
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            self.assistants = [a for a in self.assistants if a.id != assistant_id]
            print(f"✅ 助手【{assistant.name}】已删除。")
            return True
        else:
            print("❌ 未找到对应的AI助手！")
            return False

    def start_service(self, assistant_id):
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            if assistant.online:
                print(f"助手【{assistant.name}】已在运行。")
            else:
                assistant.online = True
                print(f"✅ 助手【{assistant.name}】已启动。")
            return True
        else:
            print("❌ 未找到对应的AI助手！")
            return False

    def stop_service(self, assistant_id):
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            if not assistant.online:
                print(f"助手【{assistant.name}】已停止。")
            else:
                assistant.online = False
                print(f"✅ 助手【{assistant.name}】已停止。")
            return True
        else:
            print("❌ 未找到对应的AI助手！")
            return False

    def assign_task(self, assistant_id, task):
        assistant = self.find_assistant_by_id(assistant_id)
        if assistant:
            if assistant.online:
                print(f"✅ 助手【{assistant.name}】正在执行任务: {task}")
                # 根据助手类型提供不同的任务响应
                if isinstance(assistant, DataAnalysisAssistant):
                    print(f"📊 数据分析结果: 已完成对'{task}'的数据分析")
                elif isinstance(assistant, ImageGenerationAssistant):
                    print(f"🎨 图像生成结果: 已根据'{task}'生成高质量图像")
                elif isinstance(assistant, TextGenerationAssistant):
                    print(f"📝 文本生成结果: 已根据'{task}'创作完成")
                elif isinstance(assistant, TranslationAssistant):
                    print(f"🌐 翻译结果: 已成功翻译'{task}'")
                elif isinstance(assistant, VoiceAssistant):
                    print(f"🎤 语音交互: 已处理语音任务'{task}'")
                else:
                    print(f"📋 任务结果: 已成功完成 '{task}'")
            else:
                print(f"❌ {assistant.name} 当前离线，无法执行任务。")
            return True
        else:
            print("❌ 未找到对应的AI助手！")
            return False

    def show_statistics(self):
        if not self.assistants:
            print("暂无AI助手数据。")
            return

        total = len(self.assistants)
        online_count = sum(1 for a in self.assistants if a.online)
        offline_count = total - online_count
        avg_score = sum(a.score for a in self.assistants) / total

        # 按类型统计
        type_stats = {}
        for assistant in self.assistants:
            if assistant.type not in type_stats:
                type_stats[assistant.type] = 0
            type_stats[assistant.type] += 1

        print("系统统计信息：")
        print(f"总助手数: {total}")
        print(f"在线助手数: {online_count}")
        print(f"离线助手数: {offline_count}")
        print(f"平均能力评分: {avg_score:.2f}")
        print("按类型统计:")
        for assistant_type, count in type_stats.items():
            print(f"  {assistant_type}: {count}个")


def show_menu():
    print("\n" + "=" * 10 + " AI助手管理器 " + "=" * 10)
    print("1. 查看所有AI助手列表")
    print("2. 根据ID查询助手详情")
    print("3. 添加新的AI助手")
    print("4. 根据ID修改助手信息")
    print("5. 删除AI助手（按ID）")
    print("6. 启动AI助手服务")
    print("7. 停止AI助手服务")
    print("8. 为AI助手分配任务")
    print("9. 显示系统统计信息")
    print("0. 退出系统")
    print("=" * 36)


def add_new_assistant(manager):
    print("添加新AI助手")
    print("可选的助手类型:")
    print("1. 数据分析助手")
    print("2. 图片生成助手")
    print("3. 文本生成助手")
    print("4. 翻译助手")
    print("5. 语音助手")

    try:
        type_choice = input("请选择助手类型(1-5): ").strip()
        type_mapping = {
            "1": "数据分析助手",
            "2": "图片生成助手",
            "3": "文本生成助手",
            "4": "翻译助手",
            "5": "语音助手"
        }

        if type_choice not in type_mapping:
            print("❌ 无效的类型选择！")
            return

        assistant_type = type_mapping[type_choice]

        assistant_id = input("请输入ID: ").strip()
        name = input("请输入名称: ").strip()
        version = input("请输入版本号: ").strip()
        online_input = input("是否在线？(1-是, 0-否): ").strip()
        online = online_input == "1"
        score = int(input("请输入能力评分(0-100): ").strip())

        if not all([assistant_id, name, version]):
            print("❌ 所有字段都必须填写！")
            return

        if score < 0 or score > 100:
            print("❌ 能力评分必须在0-100之间！")
            return

        # 根据类型创建对应的子类对象
        if assistant_type == "数据分析助手":
            assistant = DataAnalysisAssistant(assistant_id, name, version, online, score)
        elif assistant_type == "图片生成助手":
            assistant = ImageGenerationAssistant(assistant_id, name, version, online, score)
        elif assistant_type == "文本生成助手":
            assistant = TextGenerationAssistant(assistant_id, name, version, online, score)
        elif assistant_type == "翻译助手":
            assistant = TranslationAssistant(assistant_id, name, version, online, score)
        elif assistant_type == "语音助手":
            assistant = VoiceAssistant(assistant_id, name, version, online, score)
        else:
            assistant = AIAssistant(assistant_id, name, assistant_type, version, online, score)

        manager.add_assistant(assistant)
    except ValueError:
        print("❌ 输入格式错误，请检查ID和能力评分的格式！")


def main():
    manager = AIManager()

    # 添加一些示例数据（使用具体的子类）
    sample_assistants = [
        VoiceAssistant("101", "小智", "v1.2", True, 85),
        TextGenerationAssistant("102", "文小助", "v2.0", True, 92),
        ImageGenerationAssistant("103", "图灵", "v1.5", False, 88),
        DataAnalysisAssistant("104", "数小析", "v1.0", True, 79),
        TranslationAssistant("105", "翻译精灵", "v2.1", False, 95)
    ]

    for assistant in sample_assistants:
        manager.assistants.append(assistant)

    print("欢迎使用 AI助手管理器 v1.0")

    while True:
        show_menu()
        choice = input("请选择操作: ").strip()

        if choice == "0":
            print("感谢使用AI助手管理器，再见！")
            break
        elif choice == "1":
            manager.show_all_assistants()
        elif choice == "2":
            assistant_id = input("请输入要查询的AI助手ID: ").strip()
            manager.show_assistant_details(assistant_id)
        elif choice == "3":
            add_new_assistant(manager)
        elif choice == "4":
            assistant_id = input("请输入要修改的AI助手ID: ").strip()
            assistant = manager.find_assistant_by_id(assistant_id)
            if assistant:
                print("可修改属性列表为：name, version, online, score")
                modification = input("请输入要修改的属性和值，用空格分割: ").strip().split()
                if len(modification) == 2:
                    manager.modify_assistant(assistant_id, modification[0], modification[1])
                else:
                    print("❌ 输入格式错误！请按'属性 值'的格式输入。")
            else:
                print("❌ 未找到对应的AI助手！")
        elif choice == "5":
            assistant_id = input("请输入要删除的AI助手ID: ").strip()
            manager.delete_assistant(assistant_id)
        elif choice == "6":
            assistant_id = input("请输入要启动的AI助手ID: ").strip()
            manager.start_service(assistant_id)
        elif choice == "7":
            assistant_id = input("请输入要停止的AI助手ID: ").strip()
            manager.stop_service(assistant_id)
        elif choice == "8":
            assistant_id = input("请输入目标AI助手ID: ").strip()
            task = input("请输入任务内容: ").strip()
            manager.assign_task(assistant_id, task)
        elif choice == "9":
            manager.show_statistics()
        else:
            print("❌ 无效的选择，请重新输入！")
if __name__ == "__main__":
    main()